import { setToken } from '@/utils/storage'
import axios from 'axios'
import { ElMessage } from "element-plus";


const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_API,
})

// 请求拦截
service.interceptors.request.use((config) => {
  return config
})

// 响应拦截
service.interceptors.response.use((response) => {

  let authorization = response.headers.authorization

  if (authorization) {
    //有 authorization 则保存到localStorage
    let token = authorization.split(" ")
    token = token.length === 1 ? token[0] : token[1]
    setToken(token)

  }

  const res = response.data

  if (res.code !== 2000) {
    ElMessage.error(res.msg)
    return new Error("request Error, at request.js")
  }

  return res

})

export default service